/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fwdispstartscreen.Updater;

import fwdispstartscreen.StartFrame;
import fwdispstartscreen.StartScreenInit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *
 * @author rbs
 */
public class Version {
    
    private int version[] = new int[3];
    private StartFrame frame;
    private StartScreenInit init;


    public static Version VersionfromTxt(String txt, StartFrame frame, StartScreenInit init) throws MalformedURLException, IOException
    {
        BufferedReader file = null;
        if(txt.contains("http"))
        {
            URL txtFileUrl = new URL(txt);
            try {
                file = new BufferedReader(new InputStreamReader(txtFileUrl.openStream()));
            } catch (Exception e) {
                frame.ShowErrMsgDialog("Keine Verbindung zum Server!");
                init.setErrorTrue();
            }
        }
        else
            try{
            file = new BufferedReader(new FileReader(txt));
            }
            catch(Exception e){
                frame.ShowErrMsgDialog("Lokale Versionsdatei nicht gefunden!");
            }

        if (file != null)
        {
            Version serverVer = new Version(file.readLine());
            return serverVer;
        }
        else
        {
            return null;
        }
    }


    public static boolean isActualVersion(String web, String file, StartFrame frame, StartScreenInit init) throws MalformedURLException, IOException
    {
        Version webVersion = VersionfromTxt(web, frame, init);
        Version locVersion = VersionfromTxt(file, frame, init);
        if (locVersion == null || webVersion == null)
            return false;
        else
            return isNewer(webVersion, locVersion);
    }
    
    public Version(String input) {

        String splitted[] = input.split("\\.");

        for(int i = 0; i < 3; i++)
            version[i] = Integer.parseInt(splitted[i]);
    }

    public int getValue()
    {
        return version[0]*100 + version[1]*10 + version[2];
    }
    
    public String getString()
    {
        return version[0] + "." + version[1] + "." + version[2];
    }

    public static boolean isNewer(Version ver1, Version ver2)
    {
        return ver1.getValue() < ver2.getValue();
    }

}
